const express=require('express');
const cookieParser=require('cookie-parser');
const cookieSession=require('cookie-session');
const userService=require('../services/userService');

var router=express.Router();


router.use('/loginPage.html',async function (req,res,next) {
    var user=req.cookies.user;
    //没有cookie（cookie是代表自动登录）
    if(user=={}||user==undefined){
        console.log('cookie is null');
        next();
    }else if(user.role=='admin'){
        console.log(('role admin isn\' auto login'));
        next();
    } else{
        //自动登录
        var data=await userService.logincookie(user);
        console.log('role user auto login');
        if(data.success){
            req.session.user=data.user;

            //这个过程是客户端给发出的
            res.redirect('/views/pages/user1.html');
        }else {
            next();
        }
    }
})


// router.use('/',function(req,res,next){
//     console.log('views/');
//     next();
// })

router.use('/pages',function (req,res,next){
    console.log('/pages');
    var user=req.session.user;
    if(user=={}||user==[]||user==undefined||user==''){
        res.redirect('/views/loginPage.html');
    }else {
        next();
    }
});


router.use('/admin',function (req,res,next){
    console.log('/admin');
    var user=req.session.user;
    if(user=={}||user==[]||user==undefined||user==''){
        res.redirect('/views/loginPage.html');
    }else if(user.role=='user'){
        res.redirect('/views/pages/user1.html');
    }else {
        next();
    }
});

//views路由上做，登录使用控制
//要进入pages下面的页面，必须是已登录状态，否则全部进入/views/loginPage.html
// router.use('/pages',(req,res,next)=>{
//     var user=req.session['user'];
//
//     //没有登陆：
//     if(user==null||user=={}||user==undefined){
//         res.redirect('/views/loginPage.html');
//     }else {
//         next();
//     }
// })
exports.router=router;